package com.kfm.shop.controller;

import com.kfm.shop.domain.Order;
import com.kfm.shop.domain.Product;
import com.kfm.shop.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/order2")
@Slf4j
public class OrderController2 {

    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    RestTemplate restTemplate;

    @Resource
    ProductService productService;

    @GetMapping("/prod/{uid}/{pid}")
    public Order order(@PathVariable("uid") Integer uid, @PathVariable("pid") Integer pid) {
        // 调用商品微服务
        // List<ServiceInstance> instances = discoveryClient.getInstances("shop-product");
        // int index = new Random().nextInt(instances.size());
        // URI uri = instances.get(index).getUri(); // http://localhost:8081/pro
        String url = "product-service"; // ip + 端口
        Product forObject = restTemplate.getForObject("http://" + url + "/product/find/" + pid, Product.class);
        System.out.println(forObject);
        return null;
    }

    @GetMapping("/prod2/{uid}/{pid}")
    public Order order2(@PathVariable("uid") Integer uid, @PathVariable("pid") Integer pid) {
        Product product = productService.findById(pid);
        System.out.println(product);
        return null;
    }

    @GetMapping("/find2")
    public Product findByPid2(@RequestParam Integer id) {
        log.info("接下来要进行{}号商品信息的查询", id);
        Product pro = productService.findById(id);
        log.info("商品信息查询成功,内容为{}", pro);
        return pro;
    }

    @GetMapping("/sendTime")
    public String sendTime() {
        // 远程调用 传递 Date 类型的数据
        // 接收方 收到的是 有14个小时的时差
        productService.sendTime(new Date());
        return "time";
    }
}
